package personal.xjl._23java1studentdemo.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;

import java.io.IOException;

@Controller
@WebFilter("/")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制性转换Request的类型
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();
        //获取用户求路径
        String path = request.getRequestURI().toString();
        if (path.contains("login")) {
            filterChain.doFilter(request, response);//过滤器放行
        }else if (session.getAttribute("username") != null) {
            filterChain.doFilter(request, response);//有令牌，放行
        }
        else {
            response.sendRedirect("/login");//非法请求跳转到登入页面
        }
    }
}
